<template>
  <div class="">
    <Row style="margin: 10px 0px;">
      <label>题目</label>
      <Input placeholder="请输题目" clearable style="width: 100px" v-model="condition.questitle"></Input>
      <label style="margin-left: 10px;">题库名称</label>
      <Select v-model="condition.quesparentname" style="width:300px">
        <Option v-for="item in conqpn" :value="item.value" :key="item.value">{{ item.label }}</Option>
      </Select>
      <!-- <label style="margin-left: 10px;">二级类型</label>
      <Select v-model="condition.quesname" style="width:100px">
        <Option v-for="item in conqn" :value="item.value" :key="item.value">{{ item.label }}</Option>
      </Select> -->
      <!-- <label style="margin-left: 10px;">类型</label> -->
      <!-- <Cascader :data="data" v-model="value1" style="width: 200px;display: inline-block;"></Cascader> -->
      <span style="margin: 0px 10px;">
        <button type="button" class="ivu-btn ivu-btn-primary" @click="search($getCondition(condition))">
          <i class="ivu-icon ivu-icon-search"></i>
          <span>查询</span>
        </button>
      </span>
      <span style="margin: 0px 10px;">
        <button type="button" class="ivu-btn ivu-btn-primary" @click="addSuject()">
          <i class="ivu-icon ivu-icon-plus"></i>
          <span>新增</span>
        </button>
      </span>

      <Upload action="rs/exam/upload" class="fr" :on-success="upSuccess" :on-error="upError" :on-progress="upProgress" :show-upload-list="false">
        <Button type="ghost" icon="ios-cloud-upload-outline">批量导入</Button>
      </Upload>
    </Row>
    <Table :columns="columns" :data="model.rows" border></Table>
    <Row style="margin: 10px 0px;">
        <Page :total="model.count" :page-size="model.pageSize" show-elevator style="text-align: center;" @on-change="loadPage"></Page>
    </Row>

    <Modal :width="900" v-model="show" title="题目设置" @on-visible-change="visibleChange" :mask-closable="false">
      <Form ref="formValidate" :model="ques" :label-width="150">
        <FormItem label="题库名称">
          <Select v-model="ques.quesparentname">
            <Option v-for="item in quesparentnames" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>

        <!-- <FormItem label="本级级题库名称">
          <Select v-model="ques.quesname">
            <Option v-for="item in quesnames" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem> -->
        <FormItem label="试题类型" >
            <RadioGroup v-model="ques.questype" >
                <Radio label="单选题">单选题</Radio>
                <Radio label="多选题">多选题</Radio>
                <Radio label="判断题">判断题</Radio>
            </RadioGroup>
        </FormItem>
        <FormItem label="是否为必考题" >
            <RadioGroup v-model="ques.mustques" >
                <Radio label="是">是</Radio>
                <Radio label="否">否</Radio>
            </RadioGroup>
        </FormItem>
        <!-- <FormItem label="试题素材" >
          <div class="demo-upload-list" v-for="item in uploadList">
              <template v-if="item.status === 'finished'">
                  <img :src="item.url">
                  <div class="demo-upload-list-cover">
                      <Icon type="ios-eye-outline" @click.native="handleView(item.name)"></Icon>
                      <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                  </div>
              </template>
              <template v-else>
                  <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
              </template>
          </div>
          <Upload
              v-show="uploadList.length === 0"
              ref="upload"
              :show-upload-list="false"
              :default-file-list="defaultList"
              :on-success="handleSuccess"
              :format="['jpg','jpeg','png']"
              :max-size="2048"
              :on-format-error="handleFormatError"
              :on-exceeded-size="handleMaxSize"
              :before-upload="handleBeforeUpload"
              multiple
              type="drag"
              action="rs/exam/uploadimg"
              style="display: inline-block;width:58px;">
              <div style="width: 58px;height:58px;line-height: 58px;">
                  <Icon type="camera" size="20"></Icon>
              </div>
          </Upload>

        </FormItem> -->
        <FormItem label="题目" prop="userName">
            <Input v-model="ques.questitle" type="textarea" :rows="2" placeholder="输入题目..."></Input>
        </FormItem>
        <FormItem label="选项" prop="userName" v-if="ques.questype === '判断题'">
          <RadioGroup v-model="ques.questitle">
              <Radio label="正确" disabled>正确</Radio>
              <Radio label="错误" disabled>错误</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="选项" prop="userName" v-if="ques.questype !== '判断题'">
          <Input v-model="ques[item.key]" class="mg-top-bottom-10" v-for="(item, index) in options" :key="item.value">
              <span slot="prepend">{{item.value}}</span>
              <span slot="append" @click="deleteOption(index)" style="cursor: pointer;" v-show="index === options.length - 1">删除</span>
          </Input>
          <Button type="primary" size="large" long  @click="addOption()" v-show="!(options.length >= 10)">添加新选项</Button>
        </FormItem>
        <FormItem label="答案" ref="select">
          <Select v-model="ques.quesans" :multiple="ques.questype === '多选题'">
            <Option v-for="item in getquesanses(ques.questype)" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
        <!-- <FormItem label="答案" v-if="ques.questype === '多选题'">
          <Select v-model="ques.quesans" multiple>
            <Option v-for="item in getquesanses(ques.questype)" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem> -->
        <FormItem label="试题分析" prop="quesans">
          <Input v-model="ques.quesanl" type="textarea" :rows="4" placeholder="输入分析..."></Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="primary"  long  @click="confirm()">保存</Button>

        <Button type="text" v-show="isModify && ques.quesstatus === '0'" @click="invalid('1')">作废本道题</Button>
        <Button type="text" v-show="isModify && ques.quesstatus === '1'" @click="invalid('0')">取消作废</Button>
      </div>
    </Modal>
    <Spin size="large" fix v-if="model.state === '查询'"></Spin>

    <Modal title="试题素材" v-model="visible">
        <img :src="'https://o5wwk8baw.qnssl.com/' + imgName + '/large'" v-if="visible" style="width: 100%">
        <div slot="footer"></div>
    </Modal>
  </div>

</template>
<script>
import axios from 'axios'
import PagedList from '@/plugins/PagedList.js'
    export default {
      title: '题库管理',
        data () {
          // console.log('PagedList', PagedList);
            return {
              test: [],
              model: new PagedList('rs/sql/singleTable_OrderBy', 20,
              {items: "'*'", tablename: "'questionbank'", orderitem: "'id'"}),
              // model: new PagedList('rs/sql/adsf', 20),
              show: false,
              condition: {
                questitle: '',
                quesparentname: '',
                quesname: ''
              },
              isModify: false, // 是否修改
              ques: {
                // 试题上级题库名称
              	quesparentname: '',
              	// 试题本级题库名称
              	quesname: '',
              	// 试题标题
              	questitle: '',
              	// 试题类型（单选，多选，判断)
              	questype: '单选题',
              	// 试题选项
              	quessel1: '',
                mustques: '否',
              	// 试题选项
              	quessel2: '',
              	// 试题选项
              	quessel3: '',
              	// 试题选项
              	quessel4: '',
              	// 试题选项
              	quessel5: '',
              	// 试题选项
              	quessel6: '',
              	// 试题选项
              	quessel7: '',
              	// 试题选项
              	quessel8: '',
              	// 试题选项
              	quessel9: '',
              	// 试题选项
              	quessel10: '',
                // 试题答案
	              quesans: '',
                // 试题分析
	              quesanl: '',
                // 是否作废，1是作废
                quesstatus: '0',
              },
              options: [
                {key: 'quessel1', value: 'A'},
                {key: 'quessel2', value: 'B'},
                {key: 'quessel3', value: 'C'},
                {key: 'quessel4', value: 'D'}
              ],
                columns: [
                  {
                    title: '序号',
                    type: 'index',
                    align: 'center',
                    width: 80
                  },
                  {
                      title: '类型',
                      key: 'questype',
                      align: 'center',
                      width: 100
                  },
                  {
                      title: '上级题库名称',
                      key: 'quesparentname',
                      align: 'center',
                      width: 200
                  },
                  // {
                  //     title: '本级题库名称',
                  //     key: 'quesname',
                  //     align: 'center',
                  //     width: 200
                  // },
                  {
                      title: '题目',
                      key: 'questitle'
                  },
                  {
                      title: '是否为必考题',
                      key: 'mustques',
                      width: 80
                  },
                  {
                      title: '操作',
                      width: 100,
                      align: 'center',
                      render: (h, params) => {
                          return h('Button', {
                            props: {
                                type: 'primary'
                            },
                            on: {
                                click: () => {
                                    this.lookOrUpdate(params.row)
                                }
                            }
                          }, '相关操作');
                      }
                  }
                ],
                subjects: [],
                // 试题素材
                defaultList: [
                    {
                        'name': 'a42bdcc1178e62b4694c830f028db5c0',
                        'url': 'https://o5wwk8baw.qnssl.com/a42bdcc1178e62b4694c830f028db5c0/avatar'
                    }
                ],
                imgName: '',
                visible: false,
                uploadList: []
            };
        },
        mounted () {
          this.search('1=1')
          // 试题素材相关
          this.uploadList = this.$refs.upload.fileList;
        },
        methods: {
            search (condition) {
              this.model.search(condition)
            },
            loadPage (index) {
                // console.log(`加载第${index}页数据`);
                this.model.loadPage(index)
            },
            addSuject () {
              this.show = true
            },
            addOption () {

              let index = this.options.length + 1
              this.options.push({key: `quessel${index}`, value: this.getChar(index)})
            },
            deleteOption (index) {
              this.options.pop()
            },
            getChar (index) {
              if (index === 1) {
                return 'A'
              } else if (index === 2) {
                return 'B'
              } else if (index === 3) {
                return 'C'
              } else if (index === 4) {
                return 'D'
              } else if (index === 5) {
                return 'E'
              } else if (index === 6) {
                return 'F'
              } else if (index === 7) {
                return 'G'
              } else if (index === 8) {
                return 'H'
              } else if (index === 9) {
                return 'I'
              } else if (index === 10) {
                return 'G'
              } else if (index === 11) {
                return 'K'
              }
            },
            getquesanses (val) {
              if (this.ques.questype === '判断题') {
                return [{label: '正确', value: '正确'}, {label: '错误', value: '错误'}]
              } else {
                let arr = []
                this.options.forEach(item => {
                  arr.push({label: item.value, value: item.value})
                })
                return arr
              }
            },
            // 保存
            confirm () {
              this.model.state = '查询'
              // 将this.ques发送的后台，成功后清空ques对象
              if (this.ques.questype === '多选题') {
                this.ques.quesans = this.ques.quesans.toString()
              }
              axios.post('rs/entity/questionbank', this.ques).then(res => {
                this.clearObj()
                this.model.refresh()
              })
            },
            lookOrUpdate (row) {
              this.isModify = true
              // console.log(this.$refs.select)
              debugger

              if (row.questype === '多选题' && typeof row.quesans === 'string') {
                row.quesans = row.quesans.split(',')
              }
              this.ques = Object.assign({}, row)
              // if (this.ques.questype === '多选题') {
              //   this.ques.quesans = this.ques.quesans.split(',')
              // }
              this.show = true
            },
            visibleChange (status) {
              if (!status) {
                this.clearObj()
              }
            },
            clearObj () {
              this.show =false
              this.isModify = false
              this.model.state = '正确'
              delete this.ques.id
              Object.keys(this.ques).forEach(key => {
                this.ques[key] = ''
              })
              this.ques.quesans = []
              this.ques.questype = '单选题',
              this.ques.mustques = '否'
              this.ques.quesstatus = '0',
              this.options = [
                {key: 'quessel1', value: 'A'},
                {key: 'quessel2', value: 'B'},
                {key: 'quessel3', value: 'C'},
                {key: 'quessel4', value: 'D'}
              ]
            },
            // 作废本题
            invalid (str) {
              this.model.state = '查询'
              this.ques.quesstatus = str
              axios.post('rs/entity/questionbank', this.ques).then(res => {
                this.clearObj()
                this.model.refresh()
              })
            },
            upSuccess (res, file, fileList) {
              this.model.state = '正确'
              this.$Message.success({
                content: '批量导入成功'
              })
              this.search('1=1')
            },
            upError (error, file, fileList) {
              this.model.state = '正确'
              this.$Message.error({
                content: '上传失败'
              })
            },
            upProgress (events, file, fileList) {
              this.model.state = '查询'
            },
            // 试题素材相关
            handleView (name) {
                this.imgName = name;
                this.visible = true;
            },
            handleRemove (file) {
                const fileList = this.$refs.upload.fileList;
                this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
            },
            handleSuccess (res, file) {
                file.url = 'https://o5wwk8baw.qnssl.com/7eb99afb9d5f317c912f08b5212fd69a/avatar';
                file.name = '7eb99afb9d5f317c912f08b5212fd69a';
            },
            handleFormatError (file) {
                this.$Notice.warning({
                    title: 'The file format is incorrect',
                    desc: 'File format of ' + file.name + ' is incorrect, please select jpg or png.'
                });
            },
            handleMaxSize (file) {
                this.$Notice.warning({
                    title: 'Exceeding file size limit',
                    desc: 'File  ' + file.name + ' is too large, no more than 2M.'
                });
            },
            handleBeforeUpload () {
                const check = this.uploadList.length < 5;
                if (!check) {
                    this.$Notice.warning({
                        title: 'Up to five pictures can be uploaded.'
                    });
                }
                return check;
            }
        },
        watch: {
          'ques.questype' (val) {
            if (!this.ques.id) {
              if (val === '多选题' && !(this.ques.quesans instanceof Array)) {
                this.ques.quesans = []
              } else {
                this.ques.quesans = ''
              }
            }
          },
          'ques.quesans.length' (val) {
            if (this.ques.quesans instanceof Array) {
              this.ques.quesans = this.ques.quesans.sort()
            }
          }
        },
        computed: {
          quesparentnames () {
            return this.$getParams('题库名称')
          },
          // quesnames () {
          //   if (this.ques.quesparentname) {
          //     return this.$getTwoParams(this.ques.quesparentname)
          //   }
          //   return []
          // },
          conqpn () {
            return [{label: '全部', value: ''}, ...this.$getParams('题库名称')]
          },
          // conqn () { // 查询用的二级
          //   if (this.condition.quesparentname) {
          //     return [{label: '全部', value: ''}, ...this.$getTwoParams(this.condition.quesparentname)]
          //   }
          //   return [{label: '全部', value: ''}]
          // },

        },
        filters: {
          sortChar (value) {
            return value.sort()
          }
        },
    };
</script>
<style lang="less">
  .ivu-select-single {
    .ivu-tag-checked {
      display: none;
    }
  }
  .demo-upload-list{
        display: inline-block;
        width: 60px;
        height: 60px;
        text-align: center;
        line-height: 60px;
        border: 1px solid transparent;
        border-radius: 4px;
        overflow: hidden;
        background: #fff;
        position: relative;
        box-shadow: 0 1px 1px rgba(0,0,0,.2);
        margin-right: 4px;
    }
    .demo-upload-list img{
        width: 100%;
        height: 100%;
    }
    .demo-upload-list-cover{
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0,0,0,.6);
    }
    .demo-upload-list:hover .demo-upload-list-cover{
        display: block;
    }
    .demo-upload-list-cover i{
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin: 0 2px;
    }
</style>
